package cn.amebius.simpledocker.thread;

import cn.amebius.simpledocker.exception.DockerErrorException;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Frame;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author 阿伟
 * @date 2023/9/13 9:54
 */
public class TerminalThread extends Thread {
    private WebSocketSession session;

    private InputStream is;

    private DockerClient dc;

    private OutputStream os;

    private String containerId;

    public TerminalThread(WebSocketSession session, InputStream is, DockerClient dc, String containerId, OutputStream os) {
        this.session = session;
        this.is = is;
        this.dc = dc;
        this.os = os;
        this.containerId = containerId;
    }
    @Override
    public void run() {
        try {
            ExecCreateCmdResponse execCreateCmdResponse = dc.execCreateCmd(containerId)
                    .withCmd("bash")
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            String execId = execCreateCmdResponse.getId();
            dc.execStartCmd(execId)
                    .withDetach(false)
                    .withTty(true)
                    .withStdIn(is)
                    .exec(new ResultCallback<Frame>() {
                        @Override
                        public void onStart(Closeable closeable) {
                            System.out.println("开启！");
                        }
                        @Override
                        public void onNext(Frame frame) {
                            System.out.println("输出输出输出");
                            try {
                                session.sendMessage(new TextMessage(frame.getPayload()));
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        @Override
                        public void onError(Throwable throwable) {

                        }
                        @Override
                        public void onComplete() {

                        }
                        @Override
                        public void close() throws IOException {

                        }
                    });
        } catch (Exception e) {
            throw new DockerErrorException("Docker异常：开启terminal错误");
        }


    }
}
